package cn.piggy.service;

import cn.piggy.listener.PiggyEventSourceListener;
import cn.piggy.model.answer.AnswerRequestBody;
import cn.piggy.component.PiggyParam;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@Service
public class AnswerExecutorService extends BaseExecutorService {
    private final OkHttpClient okHttpClient;
    private final PiggyParam aiParam;
    @Autowired
    public AnswerExecutorService(OkHttpClient okHttpClient, PiggyParam aiParam) {
        super(okHttpClient);
        this.okHttpClient = okHttpClient;
        this.aiParam = aiParam;
    }

    public String syncExecute(AnswerRequestBody aiRequestBody) throws IOException {
        aiRequestBody.setStream(false);
        return executeHttpRequest(aiParam.getApiHost(), aiRequestBody);
    }

    public void asyncExecute(AnswerRequestBody aiRequestBody, HttpServletResponse response) throws IOException, InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");

        aiRequestBody.setStream(true);
        Request request = getRequestObject(aiParam.getApiHost(), aiRequestBody);

        EventSource.Factory factory = EventSources.createFactory(okHttpClient);
        factory.newEventSource(request, new PiggyEventSourceListener(response, countDownLatch));
        countDownLatch.await();
    }

    @Override
    public String queryToken() throws IOException {
        String clientId = aiParam.getClientId();
        String clientSecret = aiParam.getClientSecret();
        String authHost = aiParam.getAuthHost();
        String url = authHost+"?grant_type=client_credentials&client_id="+clientId+"&client_secret="+clientSecret;
        Request request = new Request.Builder().url(url).build();
        return requestToken(request);
    }
}
